<?php

error_reporting(E_ALL);

const BR_END = "<br>\n";

// Menu des administrateurs/utilisateurs
if (isValidConstant() != 1) {
    fermeSessionUtilisateur();
}

// ----------------------
// Droit de l'utilisateur
// ----------------------
$modeAdmin= ($_SESSION['gestion_site']>="Oui"?"Oui":"Non");
if ($modeAdmin!=="Oui") {
    exit;
}

if ($_SESSION['gestion_site']==="XXX") {
    $modeSysteme = "Oui";
} else {
    $modeSysteme = "Non";
}

//Date du moment
$dateImmediate = date("Ymd\_His");
print "Date de la copie de sauvegarde : " . $dateImmediate . BR_END;
print BR_END;

$host = 'localhost';
$username = $_ENV["SQL_USER"];
$password = $_ENV["SQL_PW"];
$database_name = 'magikweb_libweb';

// Get connection object and set the charset
$conn = mysqli_connect($host, $username, $password, $database_name);
$conn->set_charset("utf8");

// Get All Table Names From the Database
$tables = array();
$sql = "SHOW TABLES";
$result = mysqli_query($conn, $sql);

while ($row = mysqli_fetch_row($result)) {
    $tables[] = $row[0];
}

$sqlScript = "";
$cptTable = 1;
foreach ($tables as $table) {

    // Prepare SQLscript for creating table structure
    $query1 = "SHOW CREATE TABLE $table";
    $result1 = mysqli_query($conn, $query1);
    $row = mysqli_fetch_row($result1);

    $sqlScript .= "\n\n" . $row[1] . ";\n\n";

    //Copie de sauvegarde de la table en cours
    if ($modeSysteme == "Oui") {
        print "Copie de sauvegarde de " . $table . BR_END;
    } else {
        print "Copie de sauvegarde de la table #" . $cptTable . BR_END;
        $cptTable++;
    }

    $query2 = "SELECT * FROM $table";
    $result2 = mysqli_query($conn, $query2);

    $columnCount = mysqli_num_fields($result2);

    // Prepare SQLscript for dumping data for each table
    for ($i = 0; $i < $columnCount; $i++) {
        while ($row = mysqli_fetch_row($result2)) {
            $sqlScript .= "INSERT INTO $table VALUES(";
            for ($j = 0; $j < $columnCount; $j++) {
                if (isset($row[$j])) {
                    $sqlScript .= '"' . $row[$j] . '"';
                } else {
                    $sqlScript .= '""';
                }
                if ($j < ($columnCount - 1)) {
                    $sqlScript .= ',';
                }
            }
            $sqlScript .= ");\n";
        }
    }

    $sqlScript .= "\n";
}

if (!empty($sqlScript)) {
    // Save the SQL script to a backup file
    mkdir($dateImmediate);
    $backup_file_name = $dateImmediate . "/" . $database_name . '_backup_' . $dateImmediate . '.sql';
    $fileHandler = fopen($backup_file_name, 'w+');
    $number_of_lines = fwrite($fileHandler, $sqlScript);
    fclose($fileHandler);

    if ($modeSysteme == "Oui") {
        print $backup_file_name . BR_END;
    }
    print BR_END;
    print "Nombre de lignes : " . $number_of_lines . BR_END;

    if ($modeSysteme == "Oui") {

        // Download the SQL backup file to the browser
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename=' . basename($backup_file_name));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($backup_file_name));
        ob_clean();
        flush();
        readfile($backup_file_name);
        exec('rm ' . $backup_file_name);
    } else {
        //Envoyer un courriel, pour notification
        print "Le courriel a été envoyé.";
    }
}